﻿using IOA.MES.WebTool.Common;
using IOA.MES.WebTool.WebSocketSupport.CommandModels;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Forms;

namespace IOA.MES.WebTool
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        NotifyIcon notifyIcon;
        public MainWindow()
        {
            CheckSingleInstance();
            InitializeComponent();
            CreateNotifyIcon();
            this.Hide();
            InitWebSocketServer();

            var apiRoot = BaseEnv.GetStorage("ApiRoot");
            var ftp = BaseEnv.GetStorage("Ftp");
            var ftpUserName = BaseEnv.GetStorage("FtpUserName");
            var ftpPassword = BaseEnv.GetStorage("FtpPassword");
            var printer = BaseEnv.GetStorage("Printer");
            var imageFolder = BaseEnv.GetStorage("ImageFolder");
            BaseEnv.ApiRoot = apiRoot;
            BaseEnv.Ftp = ftp;
            BaseEnv.FtpUserName = ftpUserName;
            BaseEnv.FtpPassword = ftpPassword;
            BaseEnv.MarkPrinter = printer;
            BaseEnv.ImageFolder = imageFolder;

            if (!string.IsNullOrWhiteSpace(apiRoot))
            {
                var response = BaseEnv.InvokeApi<CheckUpgradeResponse>("/api/Common/CheckUpgrade", "", new { AppName = BaseEnv.LocalDirectory.Substring(BaseEnv.LocalDirectory.LastIndexOf("\\") + 1), CurrentVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion });
                if (response.ErrCode != 200)
                {
                    System.Windows.MessageBox.Show(response.ErrMsg);
                    Environment.Exit(0);
                }
                else if (response.Data.HasUpgrade)
                {
                    System.Diagnostics.Process.Start($"{BaseEnv.LocalDirectory}\\upgrade\\upgrade.exe");
                    Environment.Exit(0);
                }
            }
        }

        private void InitWebSocketServer()
        {
            var bootstrap = BootstrapFactory.CreateBootstrap();
            if (!bootstrap.Initialize())
            {
                System.Windows.MessageBox.Show("初始化服务失败！");
                Environment.Exit(0);
                return;
            }

            var result = bootstrap.Start();

            Console.WriteLine("Start result: {0}!", result);

            if (result == StartResult.Failed)
            {
                System.Windows.MessageBox.Show("启动服务失败！");
                Environment.Exit(0);
                return;
            }
        }

        /// <summary>
        /// 定义通知栏
        /// </summary>
        private void CreateNotifyIcon()
        {
            this.notifyIcon = new NotifyIcon();
            this.notifyIcon.BalloonTipText = "AISUNMes本地工具"; //设置程序启动时显示的文本
            this.notifyIcon.Text = "AISUNMes本地工具";//最小化到托盘时，鼠标点击时显示的文本
            this.notifyIcon.Icon = new System.Drawing.Icon($"{BaseEnv.LocalDirectory}\\icon.ico");
            this.notifyIcon.Visible = true;

            var settingMenu = new MenuItem("设置");
            settingMenu.Click += SettingMenu_Click;
            var existMenu = new MenuItem("退出");
            existMenu.Click += ExistMenu_Click;
            var menus = new MenuItem[] { settingMenu, existMenu };
            this.notifyIcon.ContextMenu = new ContextMenu(menus);

            this.notifyIcon.ShowBalloonTip(1000);
        }

        /// <summary>
        /// 设置
        /// </summary>
        private void SettingMenu_Click(object sender, EventArgs e)
        {
            new WinSetting().ShowDialog();
        }

        /// <summary>
        /// 退出应用
        /// </summary>
        private void ExistMenu_Click(object sender, EventArgs e)
        {
            MessageBoxResult dr = System.Windows.MessageBox.Show("退出后将无法使用MES部分功能，确定退出？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (dr == MessageBoxResult.OK)
            {
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// 检测单例
        /// </summary>
        private void CheckSingleInstance()
        {
            bool singleInstance = false;
            System.Threading.Mutex singleInstanceMutex = new System.Threading.Mutex(true, "singleInstance", out singleInstance);
            if (!singleInstance)
            {
                Environment.Exit(0);
            }
            //保持互斥量不被垃圾回收器回收
            GC.KeepAlive(singleInstance);
        }
    }
}
